<script setup lang="ts">
import {
  ruleDelFreeRuleApi,
  ruleGetFreeRuleDetailApi,
  ruleGetFreeRuleListApi,
} from '@/apis/card'
import type { FreeRuleListItemI, RuleHandleParamsI } from '@/types/card.d.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import RuleDialog from './components/RuleDialog.vue'
import { utils, writeFileXLSX } from 'xlsx'

/**
 * 表格区域
 */
// 计费规则列表参数
let params = ref({
  page: 1,
  pageSize: 5,
})
let total = ref(0)
// 计费规则列表
let freeRuleList = ref<FreeRuleListItemI[]>([])
const getFreeRuleList = async () => {
  const res = await ruleGetFreeRuleListApi(params.value)
  freeRuleList.value = res.rows
  total.value = res.total
}
getFreeRuleList()
// 删除计费规则
const delFreeRule = async (id: number) => {
  await ElMessageBox.confirm('您确定要删除该计费规则吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await ruleDelFreeRuleApi(id)
  getFreeRuleList()
  ElMessage.success('删除成功')
}
/**
 * 分页区域
 */
// 页码改变
const changePage = (page: number) => {
  params.value.page = page
  getFreeRuleList()
}
// 每页条数改变
const changePageSize = (pageSize: number) => {
  params.value.page = 1
  params.value.pageSize = pageSize
  getFreeRuleList()
}
/**
 * 弹层
 */
const dialogFlag = ref(false)
const ruleDetail = ref<RuleHandleParamsI>()
// 打开弹层
const openDialog = async (id: number) => {
  ruleDetail.value = await ruleGetFreeRuleDetailApi(id)
  dialogFlag.value = true
}
// 弹层关闭重新获取数据
const onSuccess = () => {
  ruleDetail.value = undefined
  getFreeRuleList()
}
/**
 * 导出Excel
 */
const exportToExcel = () => {
  // 表头英文字段key（需要导出字段）
  const tableHeaderKeys = [
    'ruleNumber',
    'ruleName',
    'freeDuration',
    'chargeCeiling',
    'chargeType',
    'ruleNameView',
  ]
  // 表头中文字段value（设置表头使用）
  const tableHeaderValues = [
    '计费规则编号',
    '计费规则名称',
    '免费时长(分钟)',
    '收费上限(元)',
    '计费方式',
    '计费规则',
  ]
  // 获取要导出的业务数据
  // 以excel表格的顺序调整后端数据（过滤）
  const sheetData = freeRuleList.value.map((item: any) => {
    const obj: any = {}
    tableHeaderKeys.forEach((key) => {
      obj[key] = item[key]
    })
    return obj
  })
  // 1. 创建一个新的工作簿
  const workbook = utils.book_new()
  // 2. 创建一个工作表 要求一个对象数组格式（可以根据需要创建多个）
  const worksheet = utils.json_to_sheet(sheetData)
  // 3. 把工作表添加到工作簿  Data为工作表名称
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
  // 4. 导出方法进行导出
  writeFileXLSX(workbook, '停车计费规则.xlsx')
}
</script>

<template>
  <div class="car-rule-page">
    <!-- 按钮区域 -->
    <div class="header-btn">
      <el-button type="primary" @click="dialogFlag = true"
        >增加停车计费规则</el-button
      >
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <el-table :data="freeRuleList" style="width: 100%; height: 400px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="计费规则编号" align="center" prop="ruleNumber" />
      <el-table-column label="计费规则名称" align="center" prop="ruleName" />
      <el-table-column
        label="免费时长(分钟)"
        align="center"
        prop="freeDuration"
      />
      <el-table-column
        label="收费上限(元)"
        align="center"
        prop="chargeCeiling"
      />
      <el-table-column label="计费方式" align="center">
        <template #default="{ row }">
          {{
            row.chargeType === 'duration'
              ? '时长收费'
              : row.chargeType === 'turn'
                ? '按次收费'
                : '分段收费'
          }}
        </template>
      </el-table-column>
      <el-table-column label="自费规则" align="center" prop="ruleNameView" />
      <el-table-column label="操作" align="center" width="120">
        <template #default="{ row }">
          <el-button type="text" @click="openDialog(row.id)">编辑</el-button>
          <el-button type="text" @click="delFreeRule(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.page"
      v-model:page-size="params.pageSize"
      layout="total, prev, pager, next, slot"
      :total="total"
      @current-change="changePage"
    >
      <el-select
        v-model="params.pageSize"
        style="width: 95px"
        @change="changePageSize"
      >
        <el-option label="3条/页" :value="3" />
        <el-option label="5条/页" :value="5" />
        <el-option label="10条/页" :value="10" />
      </el-select>
    </el-pagination>
    <!-- 弹层 -->
    <rule-dialog
      v-model="dialogFlag"
      :detail="ruleDetail"
      @success="onSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
// 整个容器
.car-rule-page {
  padding: 20px;
  background-color: #fff;
}
// 表格
.el-table {
  margin: 20px 0;
}
.el-pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
